# -*- coding: utf-8 -*-

# Copyright(c) 2011 OpenDomo Services SL. Licensed under GPL v3 or later
# Isidro Catalan <icatalan@opendomo.com>

from elisa.core.utils import defer
from elisa.core.utils.i18n import install_translation
from elisa.core.action import ContextualAction
from elisa.core.resource_manager import ResourceProviderNotFound
from elisa.plugins.poblesec.plugins_settings import GenericSettingsController
from elisa.plugins.poblesec.login import LoginController
from elisa.plugins.opendomo.utils import get_opendomo_provider
from elisa.plugins.opendomo import opendomo_api as opendomo
from twill import commands as twill

_ = install_translation('opendomo')
_p = install_translation('poblesec')


def opendomo_settings_decorator(controller):
    controller.append_plugin('opendomo', _('Opendomo'), '/poblesec/opendomo/settings')
    return defer.succeed(None)

class AuthenticationAction(ContextualAction):

    def __init__(self, controller):
        super(AuthenticationAction, self).__init__(controller)
        provider = get_opendomo_provider()

        if  provider.is_logged_in():
            self.name = _("Log out")
        else:
            self.name = _("Log in")

    def execute(self, item):
        provider = get_opendomo_provider()

        if provider.is_logged_in():

            self.name = _("Log in")
            provider.logout()
            dfr = defer.succeed(None)
        else:
            def controller_appended(result):

                self.name = _("Log out")
                return result

            browser = self.controller.frontend.retrieve_controllers('/poblesec/browser')[0]
            path = "/poblesec/opendomo/login"
            title = _("Log in")
            dfr = browser.history.append_controller(path, title)
            dfr.addCallback(controller_appended)

        return dfr
        


class SettingsController(GenericSettingsController):

    def populate_model(self):
        action = AuthenticationAction(self)
        action.connect('name-changed', self._action_name_changed_cb)
        model = [action,]
        return defer.succeed(model)

    def _action_name_changed_cb(self, *args):
        self.refresh()

class OpendomoLoginController(LoginController):

    """
    Specific login controller for Opendomo.
    """

    def login(self, username, password):
        # Overridden from mother class.
        try:
            provider = get_opendomo_provider()
        except ResourceProviderNotFound, error:
            return defer.fail(error)
        else:
            dfr=provider.login(username, password)
            return dfr

    def success(self, result):
#        twill.save_cookies(opendomo.COOKIE_JAR)
        res = opendomo.check_token()
        if res == False:
           raise self.failure('Authentication Failure!')

        # Overridden from mother class.
        browser = self.frontend.retrieve_controllers('/poblesec/browser')[0]
        """ paths should be filled by all the main categories of the CGI"""
        paths = [('/poblesec/plugins_menu', _p('PLUGINS'), {}),
                 ('/poblesec/opendomo/access', _('Opendomo Access'), {})]
#        return 1
        return browser.navigate(paths)
